/*
* Copyright 2005-2009 Jesse Andrews
* Copyright 2011 Stepan Riha
*
* This file may be used under the terms of of the
* GNU General Public License Version 3 or later (the "GPL"),
* http://www.gnu.org/licenses/gpl.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*/

  function find_isbn(win) {
    function checkISBN(isbnIn) {
      // prefer 10 digit ISBNs until we have a ISBN object ...
      var isbn = ISBN.validate(isbnIn);
      if (isbn) {
        if (isbn.length == 10) {
          return isbn;
        }
        return ISBN.convert(isbn) || isbn;
      }
    };

    var href = win.location.href;

	// General match on URL
	var match = href.match(/\b(\d{13}|\d{9}[0-9Xx])(\b|$)/);
    if(match && checkISBN(match[1])) {
    	return match[1];
    }


    if (href.match('amazon.com') && !href.match('rate-this')) {
      return checkISBN(href.match(/\/(\d{9}[0-9Xx])(\/|\?|$)/i)[1]);
    }

    if (href.match('booksamillion.com')) {
      return checkISBN(href.match(/isbn=(\d{9}[0-9Xx])(\&|\?|$)/)[1]);
    }

    if (href.match('barnesandnoble.com')) {
      if (href.toLowerCase().match(/isbn=/)) {
        return checkISBN( href.toLowerCase().match(/isbn=(\d{13}|\d{9}[0-9x])(\&|\?|$)/)[1] );
      }
      if (href.toLowerCase().match(/ean=/)) {
        return checkISBN( href.toLowerCase().match(/ean=(\d{13}|\d{9}[0-9x])(\&|\?|$)/)[1] );
      }
    }

    if (href.match('abebooks.com')) {
      var isbn=false;
      try {
        isbn = checkISBN( win.title.match(/ISBN (\d{13}|\d{9}[0-9Xx])/)[1] );
      } catch (e) {};
      try {
        if (!isbn) isbn = checkISBN( win.body.innerHTML.match(/class="isbn">(\d{13}|\d{9}[0-9Xx])/)[1] );
      } catch (e) {};
      return isbn;
    }

    if (href.match('buy.com')) {
      try {
        return checkISBN( win.title.match(/ISBN (\d{13}|\d{9}[0-9Xx])/)[1] );
      } catch (e) {};
    }

    if (href.match('powells.com')) {
      var dts = win.getElementsByTagName('dt');
      for (i=0; i<dts.length; i++) {
        if (dts[i].innerHTML.match('ISBN:')) {
          return checkISBN(dts[i].nextSibling.firstChild.textContent);
        }
      }
    }

    if (href.match('alibris.com')) {
      var bs = win.getElementsByTagName('b');
      for (i=0; i<bs.length; i++) {
        if (bs[i].innerHTML.match('ISBN:')) {
          return checkISBN(bs[i].nextSibling.nextSibling.textContent);
        }
      }
    }

    if (href.match('half.ebay.com')) {
      var bs = win.getElementsByTagName('b');
      for (i=0; i<bs.length; i++) {
        if (bs[i].innerHTML.match('ISBN-10:')) {
          return checkISBN(bs[i].nextSibling.nextSibling.textContent);
        }
      }
    }

    if (href.match('books.google.com')) {
      return checkISBN( href.match(/vid=ISBN(\d{13}|\d{9}[0-9Xx])/)[1] );
    }

    if (href.match('worldcatlibraries.org')) {
      // return checkISBN( href.match(/isbn\/([0-9Xx]{10})/)[1] );
    }

    if (href.match('bookmooch.com')) {
      return checkISBN( href.match(/detail\/(\d{13}|\d{9}[0-9Xx])/)[1] );
    }

    if (href.match('paperbackswap.com')) {
      return checkISBN( href.match(/details\/(\d{13}|\d{9}[0-9Xx])/)[1] );
    }

    if (href.match('nic.nils.org')) {
      var tds = win.getElementsByTagName('td');
      for (i=0; i<tds.length; i++) {
        if (tds[i].textContent == 'ISBN') {
          // occasionally has ISBN_NUMBER : $32.33
          // or 0803205198 (electronic bk.)
          return checkISBN(tds[i].nextSibling.nextSibling.textContent.match(/(\d{13}|\d{9}[0-9Xx])/)[1]);
        }
      }
    }

    // check for the ISBN microformat
    if (win.getElementsByClassName) {
      var results = win.getElementsByClassName('isbnnumber');
      if (results.length == 1) {
        var text = results[0].textContent;
        return checkISBN(text.match(/(\d{13}|\d{9}[0-9Xx])/)[1]);
      }
    }

    var isbn = href.toLowerCase().match(/isbn=(\d{13}|\d{9}[0-9x])/);
    if (isbn) return checkISBN( isbn[1] );
  }

function close_alternatives() {
	$('#bookburrito-listing').remove();
}

function create_getting_started_row() {
	var $tr = $('<tr id="bookburrito-get-started">')
		.append($('<th/>')
			.text("Get started by configuring some libraries...")
		)
		.append($('<th/>')
			.append($("<img/>")
				.attr('src', chrome.extension.getURL("html/no-options-bg.png"))
			)
		)
		.click(show_options);
	return $tr;
}

function create_row(site, isbn) {
	var id = site.id;
	var $td = $('<td class="busy">').attr('id', id)
			.append($('<img>').attr('src', chrome.extension.getURL("html/busy.gif")));
			
	var $tr = $('<tr>')
		.append($('<th>')
			.append($('<a>').text(site.title).attr('href', site.link)))
		.append($td);

	chrome.extension.sendRequest({ action: 'getBookInfo', isbn: isbn, site: site },
		function(response) {});

	return $tr;
}

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.action == "setBookInfo") {
    	var site = request.site;
    	var text = request.text;
		var id = site.id;
    	var $td = $('#' + id);
    	$td.text(text).addClass(text == 'no' ? 'bookburrito-no' : 'bookBurrito-yes');
    }
});

function show_options() {
	$('#bookburrito-alternatives').remove();
	chrome.extension.sendRequest({ action: 'showOptions' });
	return false;
}

function show_alternatives(isbn) {

	var $table = $('<table id="bookburrito-alternatives">');
	var $thead = $('<thead>').appendTo($table);
	var $tr = $('<tr class="bookburrito-header"><th><div id="bookburrito-icon"></div>BookBurrito</th></tr>')
				.appendTo($thead)
				.click(function() {
					$table.remove();
					return false;
				});
	$('#bookburrito-icon', $tr).css("background-image", "url(" + chrome.extension.getURL("icons/icon24.png") + ")");
	var $tools = $('<td></td>').appendTo($tr);
	var $prefs = $('<a href="#" class="bookburrito-icon-small"></a>')
		.attr('title', 'BookBurrito Options')
		.appendTo($tools)
		.css("background-image", "url(" + chrome.extension.getURL("html/cog_alt_16x16.png") + ")")
		.click(show_options);	
	var $tbody = $('<tbody>').appendTo($table);
	$('#bookburrito').prepend($table);

	chrome.extension.sendRequest({ action: 'getAlternatives', isbn: isbn }, function(response) {
		var sites = response.sites;
		
		if(!sites || sites.length == 0) {
			$tbody.append(create_getting_started_row());
		} else {
			for(var i = 0; i < sites.length; i++) {
				var site = sites[i];
				$tbody.append(create_row(site, isbn));
			}
		}
	});

}

var isbn = find_isbn(window);
if(isbn) {
	var $trigger = $('<span id="bookburrito-trigger" class="bookburrito"><div id="bookburrito-icon-small"/>BookBurrito</span>')
		.click(function() {
			show_alternatives(isbn);
			return false;
		});
	$('#bookburrito-icon-small', $trigger).css("background-image", "url(" + chrome.extension.getURL("icons/icon16.png") + ")");
	var $close = $('<a id="bookburrito-close" class="bookburrito-icon-small" href="#"></a>')
		.prependTo($trigger)
		.css("background-image", "url(" + chrome.extension.getURL("html/close.gif") + ")")
		.click(function() {
			$trigger.remove();
			return false;
		});
	var $bookBurrito = $('<div id="bookburrito"/>').append($trigger).prependTo($('body'));
}
